<?php

namespace app\common\model\base;

use think\Model;
use think\facade\Request;
use think\helper\Str;
use think\facade\Db;

class Base extends Model{
    
    protected $autoWriteTimestamp = false;
    //获取字段列表
    public function getColumnList()
    {
        return $this->schema ?  array_keys($this->schema) : array_column($this->getFieldList(),'Field');
    }

    //获取表名
    public function getTableName()
    {
        return $this->table ?: $this->getTblName();
    }

    //获取表名 
    public function getTblName()
    {
        $class_name=basename(str_replace('\\', '/',static::class));
        $table_name=Str::snake($class_name);
        return $this->getCurrentDbConfig('prefix').$table_name;
    }

    //获取当前连接
    public function getCurrentConnection() 
    {
        return $this->connection ?: config('database.default');
    }

    //获取当前数据库配置
    public function getCurrentDbConfig(?string $key)
    {
        $config=config('database.connections.'.$this->getCurrentConnection());
        return $key ? $config[$key] : $config;
    }    

    //获取字段列表
    public function getFieldList()
    {
        return Db::connect($this->getCurrentConnection())->query('SHOW COLUMNS FROM ' .$this->getTableName());
    }

    //获取主键
    public function getPrimaryKey()
    {
        if($this->pk){
            return $this->pk;
        }
        $fields=$this->getFieldList();
        foreach ($fields as $field) {
            if($field['Key']=='PRI'){
                return $field['Field'];
            }
        }
        return null;
    }

    //构建查询条件
    public function buildWhereCond($attr)
    {
        $cols = $this->getColumnList();
        $map = [];
        foreach ($attr as $key => $value) {
            if(!empty($value) && in_array($key,$cols)){
                $map[]=[$key,'=',$value];
            }
        }
        return $map;
    }

    //根据条件查询记录
    public function findByAttr(array $attr = [], array $columns = [])
    {
        try {
            //排序
            $order = $attr['order'] ?? null;
            //每页显示记录数量
            $limit =$attr['limit'] ?? Request::param('limit') ?? null;
            //默认20条每页
            if($limit && ($limit<=0) || $limit>100){
                $limit=20;
            }
            $query=$this::where($this->buildWhereCond($attr));
            if(!empty($order)){
                $query->order($order);
            }else{
                $pk=$this->getPrimaryKey();
                $query->order($pk,'desc');
            }
            if(!empty($columns)){
                $query->field($columns);
            }
            if ($limit) {
                return $query->paginate($limit)->toArray();
            }
            return $query->select()->toArray();
        } catch (\Throwable $t) {
            throw $t;
        }
    }
}